import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';

class SocketTestRoute extends StatefulWidget {
  const SocketTestRoute({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() => _SocketTestRouteState();
}

class _SocketTestRouteState extends State<SocketTestRoute> {
  Future<String> _request() async {
    var conn = await Socket.connect("baidu.com", 80);
    conn.writeln("GET / HTTP/1.1");
    conn.writeln("Host:baidu.com");
    conn.writeln("Connection:close");
    conn.writeln(
        "User-Agent: Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.7113.93 Safari/537.36");
    conn.writeln();
    await conn.flush();
    String _response = await utf8.decoder.bind(conn).join();
    await conn.close();
    return _response;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Socket Test'),
      ),
      body: FutureBuilder<String>(
        future: _request(),
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            return Text(snapshot.data!);
          } else {
            return const CircularProgressIndicator();
          }
        },
      ),
    );
  }
}
